package org.net5ijy.security.validate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.net5ijy.security.util.exception.ValidateCodeException;
import org.springframework.stereotype.Component;

/**
 * ImgValidateCodeValidator
 *
 * @author XGF
 * @date 2020/11/30 22:22
 */
@Component("imgValidateCodeValidator")
public class ImgValidateCodeValidator implements ValidateCodeValidator {

  public static final String IMG_CODE_PARAMETER_NAME = "img_code";

  @Override
  public boolean valid(HttpServletRequest request,
      HttpServletResponse response) {

    HttpSession session = request.getSession();

    // 从session获取存入的验证码
    ValidateCode sessionCode = (ValidateCode) session
        .getAttribute(ImgValidateCodeGenerator.IMG_VALIDATE_CODE_SESSION_KEY);

    // 删除session中的数据
    session.removeAttribute(ImgValidateCodeGenerator.IMG_VALIDATE_CODE_SESSION_KEY);
    // 获取请求中的验证码参数
    String code = request.getParameter(IMG_CODE_PARAMETER_NAME);

    if (code == null) {
      throw new ValidateCodeException("请输入验证码");
    }
    if (sessionCode == null) {
      throw new ValidateCodeException("会话验证码不存在");
    }
    // 过期
    if (sessionCode.getExpireTime() < System.currentTimeMillis()) {
      throw new ValidateCodeException("验证码超时");
    }
    // 验证码不正确
    if (!sessionCode.getCode().equalsIgnoreCase(code)) {
      throw new ValidateCodeException("验证码不正确");
    }
    return true;
  }
}
